package org.future.task.redis.serialize;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;
import org.future.task.core.serialize.MineSerializer;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class ByteMineSerializer implements MineSerializer<byte[], Object> {

    private static final ObjectMapper MAPPER = new ObjectMapper();


    @Override
    public byte[] encode(Object in) {
        String outString;
        if (!(in instanceof String)) {
            outString = objectToJson(in);
        } else {
            outString = (String) in;
        }
        // String 转 byte数组
        byte[] strByte = outString.getBytes(StandardCharsets.UTF_8);
        return strByte;
    }

    @Override
    public Object decode(byte[] in) {
        String strString = new String(in, StandardCharsets.UTF_8);
        return strString;
    }

    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String objectToJson(Object data) {
        try {
            String string = MAPPER.writeValueAsString(data);
            return string;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = MAPPER.readValue(jsonData, javaType);
            return list;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
